<template>
  <div class="display-none"></div>
</template>

<script>
  import {getStorage, setStorage, StorageKey} from '@/config/sessions';
  import {momentFormat} from '@/config/common';
  import {WidgetClass} from "@/modules/IDE/widget/atom/widget";

  const optEvent = ['mousemove', 'touchmove', 'keyup', 'mousewheel', 'DOMMouseScroll'];

  export default {
    name: 'TokenRefresh',
    props: {
      isEditor: {
        type: Boolean,
        default: () => {
          return false;
        },
      },
    },
    data() {
      return {
        tokenRefreshing: false // 标志是否正在刷新 token
      };
    },
    mounted() {
      optEvent.forEach(event => {
        window.addEventListener(event, this.userOperationHdl);
      });
      //工程和列表id不一样
      if (this.isEditor) {
        this.editorClick(this.userOperationHdl);
      } else {
        this.globalClick(this.userOperationHdl);
      }
    },

    beforeDestroy() {
      optEvent.forEach(event => {
        window.removeEventListener(event, this.userOperationHdl);
      });
    },
    methods: {
      // 用户操作事件处理
      userOperationHdl() {
        const current = moment().format(momentFormat.timestamp); // 获取当前的时间戳
        const tokenTime = parseInt(getStorage(StorageKey.tokenTime) || '0'); // 获取到保存token的时间
        const tokenLimit = parseInt(getStorage(StorageKey.tokenLimit) || '30');
         //console.log('tokenLimit token 过期的时限',tokenLimit)
        const duration = current - tokenTime; // 距离上次登录保存的 token 已经经过了多久
         //console.log('duration距离上次登录保存的token已经经过了',duration,'秒')
        const redundancy = Math.min(tokenLimit * 0.9, tokenLimit); // 开始 token 刷新的提前冗余时间（默认10分钟），0.2自定义 界限值
         //console.log('redundancy提前冗余时间',redundancy)
        // duration 没有超过 token 过期的时限，并且已经进入刷新的时间提前量区间，refreshToken有值,则进行 token 刷新
        if (!this.tokenRefreshing && duration > redundancy && duration < tokenLimit && getStorage(StorageKey.refreshToken)) {
          // console.log('重新调用token')
          this.tokenRefreshing = true;
          API.user.refreshToken({refreshToken: getStorage(StorageKey.refreshToken)}).then(resp => {
            setStorage(StorageKey.token, resp.data.token || '');
            setStorage(StorageKey.refreshToken, resp.data.refreshToken || '');
            setStorage(StorageKey.tokenTime, moment().format(momentFormat.timestamp));
            this.tokenRefreshing = false;
          }).catch(err => {
            this.tokenRefreshing = false;
          });
        }
      }
    }
  };
</script>

<style scoped>

</style>
